from sympy import symbols, diff, sympify
import sympy as sp
import tkinter as tk
from tkinter import messagebox

def solve_equation(window, equation_entry):
    x = symbols('x')  # 定义符号变量x
    equation_str = equation_entry.get()  # 获取用户输入的方程
    try:
        # 将字符串转换为表达式
        expression = sympify(equation_str)
        # 求导
        derivative = diff(expression, x)
        # 显示求导结果
        messagebox.showinfo("求导结果", f"导数为: {derivative}")
    except Exception as e:
        messagebox.showerror("错误", f"无法解析表达式: {str(e)}")


def switch(window):
    window.withdraw()  # 隐藏当前窗口
    solve_window = tk.Toplevel()  # 创建新窗口
    solve_window.title("求导")  # 界面标题
    solve_window.geometry("400x300")  # 窗口大小

    # 创建Label对象进行提示
    tk.Label(solve_window, text="请输入求导函数（例如：cos(x)）:").pack(pady=10)
    # 创建Entry对象让用户进行输入
    equation_entry = tk.Entry(solve_window, width=30)
    equation_entry.pack(pady=10)

    # 解方程按钮
    solve_button = tk.Button(solve_window, text="求导", command=lambda: solve_equation(solve_window, equation_entry))
    solve_button.pack(pady=10)

    # 添加返回按钮，返回到原始计算器
    return_button = tk.Button(solve_window, text="返回",
                              command=lambda: [solve_window.destroy(), window.deiconify()])
    return_button.pack(pady=10)
